#include "CommLog.h"
#include "Mmsystem.h"

CCommLog *CCommLog::m_pCommLog = NULL;

CCommLog::CCommLog(STRING fileName)
{
    m_hFileStream = new OFSTREAM();
    m_hFileStream->open(fileName.c_str(), ios_base::out|ios_base::app|ios_base::ate);
    InitializeCriticalSection(&m_LogCS);
}

CCommLog::~CCommLog(void)
{
    m_hFileStream->close();
    delete m_hFileStream;
}

void CCommLog::Init(STRING fileName)
{
    if (m_pCommLog != NULL)
    {
        delete m_pCommLog;
    }

    m_pCommLog = new CCommLog(fileName);
}

CCommLog* CCommLog::GetLogger()
{
    return m_pCommLog;
}

void CCommLog::Log(wstring string)
{
    EnterCriticalSection(&m_LogCS);
    *m_hFileStream << GetCurrentTimeStr() << L" - " << string << endl;
    LeaveCriticalSection(&m_LogCS);
}

void CCommLog::Log(string string)
{
    Log(s2ws(string));
}

STRING CCommLog::GetCurrentTimeStr()
{
    SYSTEMTIME sysTime;
    GetLocalTime(&sysTime);

    TCHAR timeStr[512];
    wsprintf(timeStr,
        L"%4d-%02d-%02d %02d:%02d:%02d",
        sysTime.wYear,
        sysTime.wMonth,
        sysTime.wDay,
        sysTime.wHour,
        sysTime.wMinute,
        sysTime.wSecond);
    
    return timeStr;
}
